// pages/mine/center.js
const app = getApp();

Page({
  data: {
    userInfo: {
      avatarUrl: '',
      nickName: '',
      gender: '',
      region: '',
      phone: '',
      address: ''
    }
  },

  // 新增：从后端获取用户信息
  getUserInfo() {
    const token = wx.getStorageSync('token');
    const userInfoStorage = wx.getStorageSync('userInfo');
    if (!token || !userInfoStorage || !userInfoStorage.openid) {
      this.setData({ userInfo: {} });
      return;
    }

    wx.request({
      url: 'http://localhost:8080/users/wx/' + userInfoStorage.openid,
      method: 'GET',
      header: {
        'Authorization': token
      },
      success: (res) => {
        if (res.data.success) {
          const userData = res.data.data;
          let avatarUrl = '';
          if (userData.avatar) {
            if (userData.avatar.startsWith('/images/')) {
              avatarUrl = userData.avatar;
            } else if (userData.avatar.startsWith('http')) {
              avatarUrl = userData.avatar;
            } else {
              avatarUrl = 'http://localhost:8080' + userData.avatar.replace(/^\./, '');
            }
          }
          this.setData({
            userInfo: {
              avatarUrl: avatarUrl,
              nickName: userData.nickname || '未设置昵称',
              gender: userData.gender || '',
              address: userData.address || '',
              phone: userData.phone || ''
            }
          });
          app.globalData.userInfo = this.data.userInfo;
          // 同步本地缓存
          let cache = wx.getStorageSync('userInfo') || {};
          cache.nickname = userData.nickname;
          cache.avatar = userData.avatar;
          cache.gender = userData.gender;
          cache.address = userData.address;
          cache.phone = userData.phone;
          wx.setStorageSync('userInfo', cache);
        } else {
          this.setData({ userInfo: {} });
        }
      },
      fail: () => {
        this.setData({ userInfo: {} });
      }
    });
  },

  // 更新昵称
  updateNickname(newNickname) {
    const token = wx.getStorageSync('token');
    const userInfoStorage = wx.getStorageSync('userInfo');
    if (!token || !userInfoStorage || !userInfoStorage.id) return;
    wx.request({
      url: `http://localhost:8080/users/${userInfoStorage.id}`,
      method: 'PUT',
      header: {
        'Authorization': token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        nickname: newNickname
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ 'userInfo.nickName': newNickname });
          app.globalData.userInfo.nickName = newNickname;
          let cache = wx.getStorageSync('userInfo');
          cache.nickname = newNickname;
          wx.setStorageSync('userInfo', cache);
        }
      }
    });
  },
  // 更新头像
  updateAvatar(newAvatarUrl) {
    const token = wx.getStorageSync('token');
    const userInfoStorage = wx.getStorageSync('userInfo');
    if (!token || !userInfoStorage || !userInfoStorage.id) return;
    wx.request({
      url: `http://localhost:8080/users/${userInfoStorage.id}`,
      method: 'PUT',
      header: {
        'Authorization': token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        avatar: newAvatarUrl
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ 'userInfo.avatarUrl': newAvatarUrl });
          app.globalData.userInfo.avatarUrl = newAvatarUrl;
          let cache = wx.getStorageSync('userInfo');
          cache.avatar = newAvatarUrl;
          wx.setStorageSync('userInfo', cache);
        }
      }
    });
  },
  // 更新手机号
  updatePhone(newPhone) {
    const token = wx.getStorageSync('token');
    const userInfoStorage = wx.getStorageSync('userInfo');
    if (!token || !userInfoStorage || !userInfoStorage.id) return;
    wx.request({
      url: `http://localhost:8080/users/${userInfoStorage.id}`,
      method: 'PUT',
      header: {
        'Authorization': token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        phone: newPhone
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ 'userInfo.phone': newPhone });
          app.globalData.userInfo.phone = newPhone;
          let cache = wx.getStorageSync('userInfo');
          cache.phone = newPhone;
          wx.setStorageSync('userInfo', cache);
        }
      }
    });
  },

  onLoad() {
    this.getUserInfo();
  },
  onShow() {
    this.getUserInfo();
  },

  onUnload() {
    if (this.data.userInfo) {
      app.globalData.userInfo = this.data.userInfo;
    }
  },
  goEditAvatar() {
    const that = this
    wx.navigateTo({
      url: '/pages/center/editAvatar/editAvatar',
      success(res) {
        res.eventChannel.emit('acceptDataFromCenter', { avatarUrl: that.data.userInfo.avatarUrl })
        res.eventChannel.on('updateAvatar', function(data) {
          that.setData({ 'userInfo.avatarUrl': data.avatarUrl })
          that.updateAvatar(data.avatarUrl)
        })
      }
    })
  },
  goEditNickname() {
    const that = this
    wx.navigateTo({
      url: '/pages/center/editNickname/editNickname',
      success(res) {
        res.eventChannel.emit('acceptDataFromCenter', { nickName: that.data.userInfo.nickName })
        res.eventChannel.on('updateNickname', function(data) {
          that.setData({ 'userInfo.nickName': data.nickName })
          that.updateNickname(data.nickName)
        })
      }
    })
  },
  goEditGender() {
    const that = this
    wx.navigateTo({
      url: '/pages/center/editGender/editGender',
      success(res) {
        res.eventChannel.emit('acceptDataFromCenter', { gender: that.data.userInfo.gender })
        res.eventChannel.on('updateGender', function(data) {
          that.setData({ 'userInfo.gender': data.gender })
          that.updateGender(data.gender)
        })
      }
    })
  },
  goEditRegion() {
    const that = this
    wx.navigateTo({
      url: '/pages/center/editRegion/editRegion',
      success(res) {
        res.eventChannel.emit('acceptDataFromCenter', { region: that.data.userInfo.region })
        res.eventChannel.on('updateRegion', function(data) {
          that.setData({ 'userInfo.region': data.region })
          // 可仿照添加 updateRegion 方法
        })
      }
    })
  },
  goEditPhone() {
    const that = this
    wx.navigateTo({
      url: '/pages/center/editPhone/editPhone',
      success(res) {
        res.eventChannel.emit('acceptDataFromCenter', { phone: that.data.userInfo.phone })
        res.eventChannel.on('updatePhone', function(data) {
          that.setData({ 'userInfo.phone': data.phone })
          that.updatePhone(data.phone)
        })
      }
    })
  },
  goEditAddress() {
    const that = this
    wx.navigateTo({
      url: '/pages/center/editAddress/editAddress',
      success(res) {
        res.eventChannel.emit('acceptDataFromCenter', { address: that.data.userInfo.address })
        res.eventChannel.on('updateAddress', function(data) {
          that.setData({ 'userInfo.address': data.address })
          that.updateAddress(data.address)
        })
      }
    })
  },
  // 更新性别
  updateGender(newGender) {
    const token = wx.getStorageSync('token');
    const userInfoStorage = wx.getStorageSync('userInfo');
    if (!token || !userInfoStorage || !userInfoStorage.id) return;
    wx.request({
      url: `http://localhost:8080/users/${userInfoStorage.id}`,
      method: 'PUT',
      header: {
        'Authorization': token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        gender: newGender
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ 'userInfo.gender': newGender });
          app.globalData.userInfo.gender = newGender;
          let cache = wx.getStorageSync('userInfo');
          cache.gender = newGender;
          wx.setStorageSync('userInfo', cache);
        }
      }
    });
  },
  // 更新地址
  updateAddress(newAddress) {
    const token = wx.getStorageSync('token');
    const userInfoStorage = wx.getStorageSync('userInfo');
    if (!token || !userInfoStorage || !userInfoStorage.id) return;
    wx.request({
      url: `http://localhost:8080/users/${userInfoStorage.id}`,
      method: 'PUT',
      header: {
        'Authorization': token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        address: newAddress
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ 'userInfo.address': newAddress });
          app.globalData.userInfo.address = newAddress;
          let cache = wx.getStorageSync('userInfo');
          cache.address = newAddress;
          wx.setStorageSync('userInfo', cache);
        }
      }
    });
  }
}) 